package com.cncytech.safe_space_config_test;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


public class MakeCallActivity extends AppCompatActivity {
    private static final int REQUEST_CODE = 1;

    private EditText phoneNumberEditText;
    private Button callButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_make_call);

        phoneNumberEditText = findViewById(R.id.phone_number_edit_text);
        callButton = findViewById(R.id.call_button);

        callButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取电话号码
                String phoneNumber = phoneNumberEditText.getText().toString().trim();

                // 检查权限是否已授予
                if (ActivityCompat.checkSelfPermission(MakeCallActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                    // 如果权限未授予，请求权限
                    ActivityCompat.requestPermissions(MakeCallActivity.this, new String[]{Manifest.permission.CALL_PHONE}, REQUEST_CODE);
                } else {
                    // 权限已授予，拨打电话
                    makePhoneCall(phoneNumber);
                }
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE) {
            // 检查权限是否已授予
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限已授予，拨打电话
                String phoneNumber = phoneNumberEditText.getText().toString().trim();
                makePhoneCall(phoneNumber);
            } else {
                // 权限被拒绝
                Toast.makeText(MakeCallActivity.this, "拨打电话权限被拒绝", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void makePhoneCall(String phoneNumber) {
        Intent intent = new Intent(Intent.ACTION_CALL);
        intent.setData(Uri.parse("tel:" + phoneNumber));
        startActivity(intent);
    }
}